<template>
  <div class="container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-wrapper">
        <!-- 搜索表单 -->
        <div class="search-form-section">
          <el-form :inline="true" :model="queryParams" ref="queryForm" class="demo-form-inline">
            <el-form-item label="项目名称">
              <el-input
                :model-value="selectedProject ? selectedProject.name : ''"
                placeholder="请选择项目"
                readonly
                class="selector-input"
              >
                <template #append>
                  <el-button @click="openProjectSelector" v-permission="['device:view']">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="设备类别">
              <el-select
                v-model="queryParams.type"
                placeholder="请选择设备类别"
                clearable
                filterable
                style="width: 140px"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.dictLabel"
                  :label="item.dictLabel"
                  :value="item.dictLabel"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select 
                v-model="queryParams.activate"
                placeholder="是否生效"
                clearable
                filterable
                style="width: 120px"
              >
                <el-option label="生效" :value="1" />
                <el-option label="失效" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item class="search-buttons">
              <el-button type="primary" @click="handleQuery" class="search-btn" v-permission="['device:view']">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetQuery" class="reset-btn" v-permission="['device:view']">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-buttons-section">
          <div class="button-group primary-actions">
    
          </div>
          
          <div class="button-group secondary-actions">
            <el-button type="success" @click="handleAdd" class="add-btn" v-permission="['device:edit']">
              <el-icon><Plus /></el-icon>
              新增
            </el-button>
            <el-button 
              type="danger" 
              @click="handleBatchDelete" 
              class="batch-delete-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['device:edit']"
            >
              <el-icon><Delete /></el-icon>
              批量删除 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="warning" 
              @click="handleBatchDeactivate" 
              class="batch-deactivate-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['device:edit']"
            >
              <el-icon><Close /></el-icon>
              批量失效 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="success" 
              @click="handleBatchActivate" 
              class="batch-activate-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['device:edit']"
            >
              <el-icon><Check /></el-icon>
              批量生效 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="info" 
              @click="openBatchCopyDialog" 
              class="batch-copy-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['device:edit']"
            >
              <el-icon><CopyDocument /></el-icon>
              批量复制 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button type="info" @click="handleDownloadTemplate" class="template-btn" v-permission="['device:view']">
              <el-icon><Download /></el-icon>
              下载模板
            </el-button>
            <el-button type="warning" @click="handleImport" class="import-btn" v-permission="['device:edit']">
              <el-icon><Upload /></el-icon>
              导入
            </el-button>
            <el-button type="primary" @click="handleExport" class="export-btn" v-permission="['device:view']">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <el-button type="primary" @click="openExportDialog" class="custom-export-btn" v-permission="['device:view']">
              <el-icon><Setting /></el-icon>
              自定义导出
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="list-card" shadow="never">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="dataList"
        :height="tableHeight"
        element-loading-text="加载中..."
        element-loading-background="rgba(255, 255, 255, 0.7)"
        style="width: 100%"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" width="60" label="序号" align="center" />
        <el-table-column prop="activate" label="状态" min-width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.activate ? 'success' : 'danger'">
            {{ scope.row.activate ? '生效' : '失效' }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column prop="projectName" label="项目名称" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column prop="type" label="设备类别" min-width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="sumPrice" label="总金额(元)" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="price-value">{{ formatPrice(scope.row.sumPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.createName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateName" label="更新人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.updateName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="270" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleDetail(scope.row.id)" v-permission="['device:view']">
              查看
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row.id)" :disabled="scope.row.activate === 0" v-permission="['device:edit']">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)" :disabled="scope.row.activate === 0" v-permission="['device:edit']">
              删除
            </el-button>
            <!-- <el-switch v-model="scope.row.activate"
                       class="ml-2"
                       inline-prompt
                       style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;margin-left: 15px"
                       active-text="生效"
                       inactive-text="失效"
                       :active-value="1"
                       :inactive-value="0"
                       @change="activateChange($event === 1,scope.row.id)" /> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 项目选择器对话框 -->
    <ArchiveSelector
      v-model="projectSelectorVisible"
      title="选择项目"
      :search-fields="projectSearchFields"
      :table-columns="projectTableColumns"
      :fetch-data-api="getProjectList"
      :multiple="false"
      @confirm="handleProjectSelect"
    />

    <!-- 自定义导出弹框 -->
    <el-dialog
      v-model="exportDialog.visible"
      title=""
      :width="680"
      custom-class="export-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <template #header>
        <div class="export-dialog-header">
          <div class="header-left">
            <el-icon class="header-icon"><Setting /></el-icon>
            <div>
              <div class="header-title">自定义导出设置</div>
              <div class="header-subtitle">选择您需要导出的数据字段</div>
            </div>
          </div>
          <div class="selected-count">
            已选择 {{ selectedExportFields.length }} / {{ exportFieldList.length }} 项
          </div>
        </div>
      </template>

      <div class="export-content">
        <div class="export-toolbar">
          <div class="toolbar-left">
            <el-button
              size="small"
              type="primary"
              @click="handleSelectAllFields(true)"
              :disabled="selectedExportFields.length === exportFieldList.length"
            >
              <el-icon><InfoFilled /></el-icon>
              全选
            </el-button>
            <el-button
              size="small"
              @click="handleSelectAllFields(false)"
              :disabled="selectedExportFields.length === 0"
            >
              <el-icon><Refresh /></el-icon>
              清空
            </el-button>
          </div>
          <div class="toolbar-right">
            <el-input
              v-model="fieldSearchText"
              size="small"
              placeholder="搜索字段..."
              clearable
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>

        <div class="field-list-container">
          <div class="field-grid">
            <div
              v-for="field in filteredExportFields"
              :key="field.fieldName"
              class="field-card"
              :class="{ 'selected': selectedExportFields.includes(field.fieldName) }"
              @click="toggleField(field.fieldName)"
            >
              <div class="field-card-content">
                <el-checkbox
                  :model-value="selectedExportFields.includes(field.fieldName)"
                  @change="() => toggleField(field.fieldName)"
                  @click.stop=""
                  class="field-checkbox"
                />
                <div class="field-info">
                  <div class="field-name">{{ field.displayName }}</div>
                  <div class="field-key">{{ field.fieldName }}</div>
                </div>
                <div class="field-icon">
                  <el-icon v-if="selectedExportFields.includes(field.fieldName)" class="check-icon"><InfoFilled /></el-icon>
                </div>
              </div>
            </div>
          </div>

          <div v-if="filteredExportFields.length === 0" class="empty-state">
            <el-icon class="empty-icon"><Search /></el-icon>
            <div class="empty-text">未找到匹配的字段</div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="export-footer">
          <div class="footer-info">
            <el-icon><InfoFilled /></el-icon>
            <span>将按当前查询条件导出选中字段的数据</span>
          </div>
          <div class="footer-buttons">
            <el-button @click="closeExportDialog" size="large">
              <el-icon><Delete /></el-icon>
              取消
            </el-button>
            <el-button
              type="primary"
              @click="confirmCustomExport"
              :loading="loading"
              size="large"
              :disabled="selectedExportFields.length === 0"
            >
              <el-icon><Download /></el-icon>
              导出 Excel
            </el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 批量复制弹窗 -->
    <el-dialog 
      v-model="batchCopyVisible" 
      title="批量复制设备核价" 
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-copy-content">
        <el-alert
          title="提示"
          type="info"
          description="将选中的设备核价复制到指定的目标项目中。"
          :closable="false"
          style="margin-bottom: 20px"
        />
        
        <div class="copy-info">
          <p><strong>选中记录数：</strong>{{ selectedRows.length }} 条</p>
          <p><strong>源项目：</strong>{{ selectedRows.map(row => row.projectName).filter((name, index, arr) => arr.indexOf(name) === index).join(', ') }}</p>
        </div>
        
        <el-form label-width="120px" style="margin-top: 20px">
          <el-form-item label="目标项目" required>
            <el-input
              :model-value="selectedTargetProject?.name || ''"
              placeholder="请选择目标项目"
              readonly
            >
              <template #append>
                <el-button @click="openTargetProjectSelector">选择项目</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeBatchCopyDialog">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmBatchCopy"
            :disabled="!selectedTargetProject"
          >
            确认复制
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 目标项目选择器 -->
    <ArchiveSelector
      v-model="targetProjectSelectorVisible"
      title="选择目标项目"
      :fetch-data-api="getProjectList"
      :search-fields="projectSearchFields"
      :table-columns="projectTableColumns"
      @confirm="handleTargetProjectSelect"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDevicePricingListApi, deleteDevicePricingApi, updateStatusApi, importDevicePricingApi, exportDevicePricingApi, downloadDevicePricingTemplateApi, customExportDevicePricingApi, batchUpdateStatusApi, batchCopyApi } from '@/api/devicePricing/index'
import type { DevicePricingPlan, DevicePricingQuery } from '@/api/devicePricing/type'
import { Search, Refresh, Plus, Edit, Delete, View, Download, Upload, Setting, InfoFilled, Check, Close, CopyDocument } from '@element-plus/icons-vue'
import { getListApi as getDictListApi } from "@/api/sysDictData" 
import { SysDictData } from "@/api/sysDictData/type"
import ArchiveSelector from "@/components/common/ArchiveSelector.vue"
import { getProjectDocumentListApi } from '@/api/project'
import { ProjectDocument, ProjectDocumentListParam } from '@/api/project/type'
import { formatPrice as formatPriceUtil } from '@/utils/formatter'

// 路由实例
const router = useRouter()

// 遮罩层
const loading = ref(true)
// 总条数
const total = ref(0)
// 核价表格数据
const dataList = ref<DevicePricingPlan[]>([])
// 表格高度自适应
const tableHeight = ref(0)
// 设备类别选项
const typeOptions = ref<SysDictData[]>([])

// 批量操作相关
const selectedRows = ref<any[]>([])
const tableRef = ref()

// 批量复制相关
const batchCopyVisible = ref(false)
const targetProjectSelectorVisible = ref(false)
const selectedTargetProject = ref<ProjectDocument | null>(null)

// 查询参数
const queryParams = reactive<DevicePricingQuery>({
  page: 1,
  limit: 10,
  projectId: undefined,
  type: undefined,
  activate: undefined
})

// 项目选择器相关
const projectSelectorVisible = ref(false)
const selectedProject = ref<ProjectDocument | null>(null)

// 项目状态映射
const statusOptions = [
  { value: 0, label: '进行中' },
  { value: 1, label: '已完成' },
  { value: 2, label: '已暂停' },
  { value: 3, label: '已取消' }
]

// 项目选择器搜索字段配置
const projectSearchFields = [
  { label: '项目名称', prop: 'name', type: 'input' as const },
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '客户名称', prop: 'customer', type: 'input' as const },
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions
  }
]

// 项目选择器表格列配置
const projectTableColumns = [
  { prop: 'name', label: '项目名称', width: 250 },
  { prop: 'code', label: '项目编号', width: 250 },
  { prop: 'customer', label: '客户名称', width: 250 },
  { prop: 'manager', label: '项目经理', width: 200 }
]

// 自定义导出相关状态
interface ExportFieldInfo {
  fieldName: string;
  displayName: string;
}

// 可导出字段列表
const exportFieldList = ref<ExportFieldInfo[]>([
  { fieldName: 'projectName', displayName: '项目名称' },
  { fieldName: 'type', displayName: '设备类别' },
  { fieldName: 'sumPrice', displayName: '总金额(元)' },
  { fieldName: 'createTime', displayName: '创建时间' },
  { fieldName: 'stackerQuantity', displayName: '堆垛机数量' },
  { fieldName: 'shelfHeight', displayName: '货架高度(m)' },
  { fieldName: 'aisleLength', displayName: '巷道长度(m)' },
  { fieldName: 'aisleWidth', displayName: '巷道宽度(mm)' },
  { fieldName: 'lengthL', displayName: '长L(m)' },
  { fieldName: 'widthW', displayName: '宽W(m)' },
  { fieldName: 'heightH', displayName: '高H(m)' },
  { fieldName: 'cargoWeight', displayName: '货物重量(kg)' },
  { fieldName: 'forkType', displayName: '货叉类型' },
  { fieldName: 'forkWeight', displayName: '货叉重量(kg)' },
  { fieldName: 'walkSpeed', displayName: '满载行走速度(m/min)' },
  { fieldName: 'walkAcceleration', displayName: '满载行走加速度(m/s2)' },
  { fieldName: 'liftSpeed', displayName: '满载提升速度(m/min)' },
  { fieldName: 'liftAcceleration', displayName: '满载提升加速度(m/s2)' },
  { fieldName: 'communicationMethod', displayName: '通讯方式' },
  { fieldName: 'positioningMethod', displayName: '定位方式' },
  { fieldName: 'plc', displayName: 'PLC' },
  { fieldName: 'inverter', displayName: '变频器' },
  { fieldName: 'photoelectricSwitch', displayName: '光电开关' },
  { fieldName: 'groundStationQuantity', displayName: '地面站数量' },
  { fieldName: 'slideLineInstallation', displayName: '滑触线安装方式' },
  { fieldName: 'energyEfficiencyLevel', displayName: '能效等级要求' },
  { fieldName: 'steelPrice', displayName: '当前钢材价格' },
  { fieldName: 'walkMotor', displayName: '行走电机' },
  { fieldName: 'liftMotor', displayName: '提升电机' },
  { fieldName: 'fork', displayName: '货叉' },
  { fieldName: 'environment', displayName: '使用环境' },
  { fieldName: 'railType', displayName: '轨道类型' },
  { fieldName: 'singleMonitoring', displayName: '单机监控' },
  { fieldName: 'aisleRadar', displayName: '巷道激光雷达' },
  { fieldName: 'armorFireExtinguisher', displayName: '铠甲/灭火器' },
  { fieldName: 'dustControl', displayName: '金属粉尘管控' },
  { fieldName: 'barcodeBelt', displayName: '条码带(米)' },
  { fieldName: 'slideLine', displayName: '滑触线' },
  { fieldName: 'transportation', displayName: '运输' },
  { fieldName: 'remark', displayName: '备注' }
])

// 自定义导出弹窗状态
const exportDialog = reactive({
  visible: false
})

// 选中的导出字段
const selectedExportFields = ref<string[]>([])

// 字段搜索文本
const fieldSearchText = ref('')

// 过滤后的导出字段列表
const filteredExportFields = computed(() => {
  if (!fieldSearchText.value) {
    return exportFieldList.value
  }
  return exportFieldList.value.filter(field =>
    field.displayName.toLowerCase().includes(fieldSearchText.value.toLowerCase()) ||
    field.fieldName.toLowerCase().includes(fieldSearchText.value.toLowerCase())
  )
})

// 获取设备类别字典
const getTypeOptions = async () => {
  try {
    const res = await getDictListApi({
      dictType: 'ConveyorType', // 假设使用与输送机相同的类型字典
      dictLabel: "",
      status: undefined,
      page: 0,
      limit: 100
    })
    if (res && res.data) {
      typeOptions.value = res.data.list || []
    }
  } catch (error) {
    console.error('获取设备类别列表失败:', error)
  }
}

// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10
    }

    // 调用项目列表API
    return await getProjectDocumentListApi(queryParams)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return { data: { list: [], total: 0 } }
  }
}

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project
  queryParams.projectId = project.id
}

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true
}

// 查询设备核价列表
const getList = async () => {
  loading.value = true
  isDataLoaded.value = false // 数据加载开始，设置标志位为false
  try {
    const res = await getDevicePricingListApi(queryParams)
    if (res && res.data) {
      dataList.value = res.data.list || []
      total.value = res.data.total || 0
    }
    // 使用nextTick确保DOM更新完成后再设置标志位
    await nextTick()
    isDataLoaded.value = true // 数据加载完成，设置标志位为true
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  selectedProject.value = null
  queryParams.projectId = undefined
  queryParams.type = undefined
  queryParams.activate = undefined
  queryParams.page = 1
  getList()
}

// 修改设备核价单的状态
const updateStatus = reactive({
  id: undefined as number | undefined,
  activate: undefined as boolean | undefined
})

// 标志位：防止初始化时触发
const isDataLoaded = ref(false)

// 激活 失效
const activateChange = async (val: boolean, id: number) => {
  // 如果数据还没加载完成，不执行更新操作
  if (!isDataLoaded.value) return
  
  updateStatus.id = id
  updateStatus.activate = val
  try {
    await updateStatusApi({ id, activate: val ? 1 : 0 })
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 新增按钮操作
const handleAdd = () => {
  router.push('/compute/devicePricing/form')
}

// 修改按钮操作
const handleEdit = (id: number) => {
  // 检查对应记录的状态
  const record = dataList.value.find(item => item.id === id)
  if (record && record.activate === 0) {
    ElMessage.warning('该设备核价单已失效，不允许编辑')
    return
  }
  router.push(`/compute/devicePricing/form/${id}`)
}

// 查看按钮操作
const handleDetail = (id: number) => {
  router.push(`/compute/devicePricing/form/${id}?display=true`)
}

// 删除按钮操作
const handleDelete = (id: number) => {
  // 检查对应记录的状态
  const record = dataList.value.find(item => item.id === id)
  if (record && record.activate === 0) {
    ElMessage.warning('该设备核价单已失效，不允许删除')
    return
  }
  
  ElMessageBox.confirm('是否确认删除该设备核价记录？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDevicePricingApi(id).then(() => {
      getList()
      ElMessage.success('删除成功')
    })
  })
}

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  // 检查选中的记录中是否有已失效的
  const invalidRecords = selectedRows.value.filter(item => item.activate === 0)
  if (invalidRecords.length > 0) {
    ElMessage.warning(`选中的记录中有${invalidRecords.length}条已失效，不允许删除操作`)
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条数据吗？`, '批量删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.id).filter(id => id)
    // 这里需要后端提供批量删除API，暂时使用循环删除
    for (const id of ids) {
      await deleteDevicePricingApi(id)
    }
    ElMessage.success('批量删除成功')
    getList()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量失效
const handleBatchDeactivate = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要失效的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要将选中的${selectedRows.value.length}条记录设为失效吗？`, '批量失效确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.id).filter(id => id)
    await batchUpdateStatusApi({ ids, activate: 0 })
    ElMessage.success('批量失效成功')
    getList()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量失效失败:', error)
      ElMessage.error('批量失效失败')
    }
  }
}

// 批量生效
const handleBatchActivate = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要生效的记录')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要将选中的${selectedRows.value.length}条记录设为生效吗？`, '批量生效确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.id).filter(id => id)
    await batchUpdateStatusApi({ ids, activate: 1 })
    ElMessage.success('批量生效成功')
    getList()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量生效失败:', error)
      ElMessage.error('批量生效失败')
    }
  }
}

// 打开批量复制弹窗
const openBatchCopyDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要复制的记录')
    return
  }
  
  // 允许复制失效数据，复制后自动生效
  
  batchCopyVisible.value = true
}

// 关闭批量复制弹窗
const closeBatchCopyDialog = () => {
  batchCopyVisible.value = false
  selectedTargetProject.value = null
}

// 打开目标项目选择器
const openTargetProjectSelector = () => {
  targetProjectSelectorVisible.value = true
}

// 处理目标项目选择
const handleTargetProjectSelect = (project: ProjectDocument) => {
  selectedTargetProject.value = project
  console.log('选择的目标项目:', project)
}

// 确认批量复制
const confirmBatchCopy = async () => {
  if (!selectedTargetProject.value) {
    ElMessage.warning('请选择目标项目')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要将选中的${selectedRows.value.length}条设备核价复制到项目"${selectedTargetProject.value.name}"吗？`, '批量复制确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const sourceIds = selectedRows.value.map(row => row.id).filter(id => id)
    await batchCopyApi({
      sourceIds,
      targetProjectId: selectedTargetProject.value.id!
    })
    
    ElMessage.success(`成功复制${sourceIds.length}条设备核价`)
    closeBatchCopyDialog()
    getList()
    
    // 清空选中状态
    selectedRows.value = []
    tableRef.value?.clearSelection()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量复制失败:', error)
      ElMessage.error('批量复制失败')
    }
  }
}

// 每页条数改变
const handleSizeChange = (size: number) => {
  queryParams.limit = size
  getList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  queryParams.page = page
  getList()
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 格式化金额 - 使用统一的格式化函数
const formatPrice = formatPriceUtil

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    await downloadDevicePricingTemplateApi()
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  }
}

// 导入
const handleImport = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.onchange = async (event: any) => {
    const file = event.target.files[0]
    if (!file) return
    
    // 验证文件类型
    const validTypes = [
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-excel'
    ]
    if (!validTypes.includes(file.type)) {
      ElMessage.error('请选择Excel文件')
      return
    }
    
    try {
      loading.value = true
      const response = await importDevicePricingApi(file)
      if (response.code === 200) {
        ElMessage.success('导入成功')
        getList() // 刷新列表
      } else {
        ElMessage.error(response.message || '导入失败')
      }
    } catch (error) {
      console.error('导入失败:', error)
      ElMessage.error('导入失败')
    } finally {
      loading.value = false
      // 清空文件输入框
      event.target.value = ''
    }
  }
  input.click()
}

// 导出
const handleExport = async () => {
  try {
    loading.value = true
    queryParams.limit = 9999

    await exportDevicePricingApi(queryParams)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 打开自定义导出对话框
const openExportDialog = () => {
  exportDialog.visible = true
  // 默认选中所有字段
  selectedExportFields.value = exportFieldList.value.map(field => field.fieldName)
}

// 关闭自定义导出弹窗
const closeExportDialog = () => {
  exportDialog.visible = false
}

// 切换字段选中状态
const toggleField = (fieldName: string) => {
  const index = selectedExportFields.value.indexOf(fieldName)
  if (index > -1) {
    selectedExportFields.value.splice(index, 1)
  } else {
    selectedExportFields.value.push(fieldName)
  }
}

// 全选/取消全选导出字段
const handleSelectAllFields = (checked: boolean) => {
  if (checked) {
    selectedExportFields.value = exportFieldList.value.map(field => field.fieldName)
  } else {
    selectedExportFields.value = []
  }
}

// 确认自定义导出
const confirmCustomExport = async () => {
  if (selectedExportFields.value.length === 0) {
    ElMessage.warning('请至少选择一个导出字段')
    return
  }

  try {
    loading.value = true
    // 移除分页参数，确保导出所有数据
    const { page, limit, ...exportParams } = queryParams
    // 检查是否有查询条件
    const hasConditions = Object.keys(exportParams).some(key => {
      const value = (exportParams as any)[key]
      return value !== undefined && value !== null && value !== ''
    })
    if (hasConditions) {
      ElMessage.info('正在导出符合当前查询条件的数据...')
    } else {
      ElMessage.info('正在导出全部数据...')
    }
    // 调用自定义导出API，传入选中的字段和查询条件
    const res = await customExportDevicePricingApi({
      exportFields: selectedExportFields.value,
      queryParams: exportParams as any
    })
    // Blob处理下载
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `设备核价自定义导出_${new Date().toISOString().slice(0, 19).replace(/[-T:]/g, '')}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
    closeExportDialog()
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getTypeOptions()
  getList()
  
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    nextTick(() => {
      tableHeight.value = window.innerHeight - 260
    })
  })
})
</script>

<style lang="scss" scoped>
.container {
  background: #f5f7fa;
  padding: 20px;
  min-height: calc(100vh - 60px);
}

.search-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
  
  .search-wrapper {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  // 搜索表单区域
  .search-form-section {
    .demo-form-inline {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: flex-end;
      
      .el-form-item {
        margin-bottom: 0;
        
        .el-input {
          border-radius: 8px;
          
          .el-input__wrapper {
            transition: all 0.3s ease;
            
            &:hover {
              box-shadow: 0 0 0 1px #409eff inset;
            }
          }
        }
        
        .el-select {
          .el-input__wrapper {
            border-radius: 8px;
            transition: all 0.3s ease;
            
            &:hover {
              box-shadow: 0 0 0 1px #409eff inset;
            }
          }
        }
        
        &.search-buttons {
          .el-button {
            margin-right: 8px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
            
            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
            }
            
            &.search-btn {
              background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
              border: none;
              color: white;
              
              &:hover {
                background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
              }
            }
            
            &.reset-btn {
              background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
              border: none;
              color: white;
              
              &:hover {
                background: linear-gradient(135deg, #F78989 0%, #F56C6C 100%);
              }
            }
          }
        }
      }
    }
  }
  
  // 操作按钮区域
  .action-buttons-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    
    .button-group {
      display: flex;
      gap: 10px;
      
      .el-button {
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        
        &.add-btn {
          background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
          border: none;
          color: white;
          padding: 10px 20px;
          
          &:hover {
            background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
          }
        }
        
        &.template-btn {
          background: linear-gradient(135deg, #909399 0%, #B3B8C0 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #B3B8C0 0%, #909399 100%);
          }
        }
        
        &.import-btn {
          background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #F7BA2A 0%, #E6A23C 100%);
          }
        }
        
        &.export-btn {
          background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
          }
        }
        
        &.custom-export-btn {
          background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
          }
        }
      }
    }
    

  }
}

.list-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none;
  
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    .el-table__header-wrapper {
      .el-table__header {
        th {
          background: #f8fafc;
          color: #606266;
          font-weight: 600;
          border-bottom: 1px solid #e4e7ed;
        }
      }
    }
    
    .el-table__body-wrapper {
      .el-table__body {
        tr:hover {
          background-color: #f8fafc;
        }
        
        td {
          border-bottom: 1px solid #ebeef5;
        }
      }
    }
    
    .el-button {
      border-radius: 6px;
      
      &.el-button--small {
        padding: 5px 12px;
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  
  :deep(.el-pagination) {
    .el-pager li {
      border-radius: 6px;
    }
    
    .btn-prev,
    .btn-next {
      border-radius: 6px;
    }
  }
}

.price-value {
  color: #E6A23C;
  font-weight: 600;
}

.date-value {
  color: #909399;
}

// 自定义导出弹窗样式
:deep(.export-dialog) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);

  .el-dialog__header {
    padding: 0;
    margin-right: 0;
    border-bottom: none;
  }

  .el-dialog__body {
    padding: 0;
  }

  .el-dialog__footer {
    padding: 0;
    border-top: none;
  }
}

.export-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 20px;
  background: linear-gradient(135deg, #409eff 0%, #1989fa 100%);
  color: white;

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;

    .header-icon {
      font-size: 28px;
      background: rgba(255, 255, 255, 0.2);
      padding: 12px;
      border-radius: 50%;
      backdrop-filter: blur(10px);
    }

    .header-title {
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .header-subtitle {
      font-size: 14px;
      opacity: 0.9;
    }
  }

  .selected-count {
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(10px);
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    border: 1px solid rgba(255, 255, 255, 0.2);
  }
}

.export-content {
  padding: 24px;

  .export-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px 20px;
    background: #f8fafc;
    border-radius: 10px;
    border: 1px solid #e2e8f0;

    .toolbar-left {
      display: flex;
      gap: 12px;

      .el-button {
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        &:disabled {
          transform: none;
          box-shadow: none;
        }
      }
    }

    .toolbar-right {
      :deep(.el-input) {
        .el-input__wrapper {
          border-radius: 8px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
          border: 1px solid #e2e8f0;
          transition: all 0.3s;

          &:hover, &.is-focus {
            border-color: #409eff;
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
          }
        }
      }
    }
  }

  .field-list-container {
    .field-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 16px;
      max-height: 400px;
      overflow-y: auto;
      padding-right: 8px;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 3px;

        &:hover {
          background: #94a3b8;
        }
      }
    }

    .field-card {
      background: white;
      border: 2px solid #e2e8f0;
      border-radius: 12px;
      padding: 16px;
      cursor: pointer;
      transition: all 0.3s ease;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

      &:hover {
        border-color: #409eff;
        transform: translateY(-4px);
        box-shadow: 0 8px 24px rgba(64, 158, 255, 0.15);
      }

      &.selected {
        border-color: #409eff;
        background: linear-gradient(135deg, #f0f4ff 0%, #e6f0ff 100%);
        box-shadow: 0 4px 16px rgba(64, 158, 255, 0.2);

        .field-card-content {
          .field-name {
            color: #409eff;
            font-weight: 600;
          }

          .field-key {
            color: #1989fa;
          }
        }
      }

      .field-card-content {
        display: flex;
        align-items: center;
        gap: 12px;

        .field-checkbox {
          flex-shrink: 0;

          :deep(.el-checkbox__input) {
            .el-checkbox__inner {
              border-radius: 6px;
              border-width: 2px;
              width: 18px;
              height: 18px;

              &:hover {
                border-color: #409eff;
              }
            }

            &.is-checked .el-checkbox__inner {
              background-color: #409eff;
              border-color: #409eff;
            }
          }
        }

        .field-info {
          flex: 1;
          min-width: 0;

          .field-name {
            font-size: 15px;
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 4px;
            word-break: break-all;
          }

          .field-key {
            font-size: 12px;
            color: #64748b;
            font-family: 'Monaco', 'Menlo', monospace;
            background: #f1f5f9;
            padding: 2px 6px;
            border-radius: 4px;
            display: inline-block;
          }
        }

        .field-icon {
          flex-shrink: 0;
          width: 24px;
          height: 24px;
          display: flex;
          align-items: center;
          justify-content: center;

          .check-icon {
            font-size: 18px;
            color: #409eff;
            animation: checkIn 0.3s ease;
          }
        }
      }
    }

    .empty-state {
      text-align: center;
      padding: 60px 20px;
      color: #64748b;

      .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
        opacity: 0.5;
      }

      .empty-text {
        font-size: 16px;
      }
    }
  }
}

.export-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;

  .footer-info {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #64748b;
    font-size: 14px;

    .el-icon {
      color: #409eff;
    }
  }

  .footer-buttons {
    display: flex;
    gap: 12px;

    .el-button {
      border-radius: 8px;
      font-weight: 500;
      padding: 12px 24px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }

      &.el-button--primary {
        background: linear-gradient(135deg, #409eff 0%, #1989fa 100%);
        border: none;

        &:hover {
          opacity: 0.9;
        }

        &:disabled {
          background: #e2e8f0;
          color: #94a3b8;
          transform: none;
          box-shadow: none;
        }
      }

      .el-icon {
        margin-right: 6px;
      }
    }
  }
}

@keyframes checkIn {
  0% {
    transform: scale(0) rotate(180deg);
    opacity: 0;
  }
  100% {
    transform: scale(1) rotate(0deg);
    opacity: 1;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .search-wrapper {
    .action-buttons-section {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;
      
      .button-group {
        justify-content: center;
        flex-wrap: wrap;
      }
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 10px;
  }
  
  .search-wrapper {
    padding: 15px;
    
    .search-form-section {
      .demo-form-inline {
        flex-direction: column;
        align-items: stretch;
        
        .el-form-item {
          width: 100%;
          
          .el-input,
          .el-select {
            width: 100% !important;
          }
          
          &.search-buttons {
            display: flex;
            gap: 8px;
            
            .el-button {
              flex: 1;
              margin-right: 0;
            }
          }
        }
      }
    }
    
    .action-buttons-section {
      .button-group {
        .el-button {
          flex: 1;
          min-width: 0;
          text-align: center;
        }
      }
    }
  }
  
  // 移动端自定义导出弹窗适配
  :deep(.export-dialog) {
    width: 95vw !important;
    margin: 5vh auto;
  }

  .export-dialog-header {
    padding: 20px 16px 16px;

    .header-left {
      gap: 12px;

      .header-icon {
        font-size: 24px;
        padding: 10px;
      }

      .header-title {
        font-size: 18px;
      }

      .header-subtitle {
        font-size: 13px;
      }
    }

    .selected-count {
      padding: 6px 12px;
      font-size: 13px;
    }
  }

  .export-content {
    padding: 16px;

    .export-toolbar {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;
      padding: 12px 16px;

      .toolbar-left {
        justify-content: center;
      }

      .toolbar-right {
        :deep(.el-input) {
          width: 100% !important;
        }
      }
    }

    .field-list-container {
      .field-grid {
        grid-template-columns: 1fr;
        gap: 12px;
        max-height: 300px;
      }

      .field-card {
        padding: 12px;

        .field-card-content {
          gap: 10px;

          .field-info {
            .field-name {
              font-size: 14px;
            }

            .field-key {
              font-size: 11px;
            }
          }
        }
      }
    }
  }

  .export-footer {
    flex-direction: column;
    gap: 12px;
    padding: 16px;

    .footer-info {
      text-align: center;
      font-size: 13px;
    }

    .footer-buttons {
      width: 100%;
      justify-content: center;

      .el-button {
        flex: 1;
        padding: 10px 20px;
      }
    }
  }
}
</style> 